package com.whiteape.book.ui.activity;

import android.widget.TextView;

import com.whiteape.book.R;
import com.whiteape.book.core.manager.MediaStorageManager;
import com.whiteape.book.core.manager.WebMediaManager;
import com.whiteape.book.model.bo.ChapterContentBo;
import com.whiteape.book.model.bo.SearchResultBo;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.dto.MediaChapterBean;
import com.whiteape.book.model.dto.SiteSourceBean;
import com.whiteape.book.model.type.DownloadStatus;
import com.whiteape.book.model.type.MediaType;
import com.whiteape.book.ui.base.BaseActivity;
import com.whiteape.book.utils.GsonUtils;
import com.whiteape.book.utils.LogUtils;
import com.whiteape.book.utils.RxUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;

public class DebugActivity extends BaseActivity {
    @BindView(R.id.tv_debug)
    TextView tvDebug;

    long timeStart;

    @Override
    protected int getContentId() {
        return R.layout.activity_debug;
    }

    private String getCurDebugTime() {
        long cur = System.currentTimeMillis();
        return String.format("%.3f",(cur - timeStart) / 1000.0f);
    }

    private void debugRecord(String msg) {
        tvDebug.append("[" + getCurDebugTime() + "] " + msg + "\n");
    }

    @Override
    protected void startLogic() {
        super.startLogic();

        timeStart = System.currentTimeMillis();
        tvDebug.append("[0.000] 开始，搜索关键字【天下】...\n");
        String query = "天下";
        SiteSourceBean siteSourceBean = (SiteSourceBean) getIntent().getSerializableExtra("siteSourceBean");
        List<SiteSourceBean> siteSourceBeanList = new ArrayList<>();
        siteSourceBeanList.add(siteSourceBean);
        Disposable disp = WebMediaManager.getInstance().getSearchInfoBySiteList(query, siteSourceBeanList)
                .compose(RxUtils::toSimpleFlowable)
                .subscribe(beans -> {
                    debugRecord("搜索到结果，一共" + beans.size() + "条数据");
                    debugRecord("第一条是 " + beans.get(0).getTitle());
                    debugRecord("获取"+beans.get(0).getTitle() + "的详情页信息(" + beans.get(0).getDetailUrl() + ")...");
                    getDetailInfo(beans.get(0));

                }, e -> {
                    LogUtils.e(e);
                    debugRecord("发生异常:" + e.getLocalizedMessage());
                });
        addDisposable(disp);
    }

    private void getDetailInfo(SearchResultBo resultBean) {
        CollectionMediaBean collectionMediaBean = new CollectionMediaBean();


        collectionMediaBean.setMediaType(resultBean.getMediaType());
        collectionMediaBean.setAuthor(resultBean.getAuthor());
        collectionMediaBean.setCoverUrl(resultBean.getCoverUrl());
        collectionMediaBean.setId(resultBean.getDetailUrl());
        collectionMediaBean.setCategory(resultBean.getCategory());
        collectionMediaBean.setDesc(resultBean.getDesc());
        collectionMediaBean.setLastChapter(resultBean.getLastChapter());
        collectionMediaBean.setLastUpdated(resultBean.getLastUpdated());
        collectionMediaBean.setState(resultBean.getState());
        collectionMediaBean.setTitle(resultBean.getTitle());
        collectionMediaBean.setWordCount(resultBean.getWordCount());
        collectionMediaBean.setSiteSourceBean(resultBean.getSiteSourceBean());
        collectionMediaBean.setVarMap(resultBean.getVarMap());
        WebMediaManager
                .getInstance()
                .getMediaInfo(collectionMediaBean)
                .compose(RxUtils::toSimpleSingle)
                .subscribe(new SingleObserver<CollectionMediaBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onSuccess(CollectionMediaBean bean) {
                        boolean hasCatalog = (bean.getMediaChapterList() != null && bean.getMediaChapterList().size() > 0);
                        debugRecord("获取详情页信息成功,包含目录?" + hasCatalog);
                        if (!hasCatalog) {
                            debugRecord("获取目录信息");
                            getCatalog(collectionMediaBean);

                        } else {
                            debugRecord("目录一共有" + bean.getMediaChapterList().size() + "章");
                            debugRecord("获取第一章内容...");
                            if (bean.getSiteSourceBean().getSiteType() == MediaType.MEDIA_TYPE_NOVEL) {
//                                getNovelContent(bean.getSiteSourceBean(), bean.getMediaChapterList().get(0).getLink());

                            } else if (bean.getSiteSourceBean().getSiteType() == MediaType.MEDIA_TYPE_COMIC) {
//                                getComicContent(bean.getSiteSourceBean(),bean, bean.getMediaChapterList().get(0));

                            }
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        debugRecord("发生异常，" + e.getLocalizedMessage());
                    }
                });
    }

    private void getCatalog(CollectionMediaBean collectionMediaBean) {
//        Disposable disposable = WebMediaManager.getInstance()
//                .getCatalog(collectionMediaBean.getSiteSourceBean(), collectionMediaBean)
//                .compose(RxUtils::toSimpleSingle)
//                .subscribe(
//                        beans -> {
//                            LogUtils.d("loadWebCatalog, onSuccess, beans is " + beans);
////                            mView.updateCatalog(beans);
//                            if (beans.size() > 0) {
//                                debugRecord("目录获取成功，一共有" + beans.size() + "章");
//
//
//                            } else {
//                                debugRecord("，目录获取失败，结果为空");
//                            }
//                        }
//                        ,
//                        e -> {
//                            LogUtils.e(e);
//                            e.printStackTrace();
//                            debugRecord("发生异常，" + e.getLocalizedMessage());
//
//                        }
//                );
//        addDisposable(disposable);

    }

//    private void getNovelContent(SiteSourceBean siteSourceBean, String contentUrl) {
//
//        Disposable disposable = WebMediaManager.getInstance().getBookChapterContent(siteSourceBean, contentUrl)
//                .compose(RxUtils::toSimpleSingle)
//                .subscribe(chapterContentBoList -> {
//                    StringBuilder sb = new StringBuilder();
//                    for (ChapterContentBo chapterContentBo : chapterContentBoList) {
//                        sb.append(chapterContentBo.getContent());
//
//                    }
//                    debugRecord("获取到内容，" + sb.toString().substring(0, sb.length() > 50 ? 50 : sb.length())+"...");
//
//                }, throwable -> {
//                    debugRecord("发生异常，" + throwable.getLocalizedMessage());
//                });
//        addDisposable(disposable);
//    }

    private void getComicContent(SiteSourceBean siteSourceBean, CollectionMediaBean collectionMediaBean, MediaChapterBean chapterBean) {

        Disposable disposable = WebMediaManager.getInstance().getComicChapterContent(siteSourceBean, collectionMediaBean,chapterBean)
                .compose(RxUtils::toSimpleSingle)
                .subscribe(chapterContentBoList -> {
                    String content = GsonUtils.obj2String(chapterContentBoList);

                    debugRecord("获取到内容，"+content);

                }, throwable -> {
                    debugRecord("发生异常，" + throwable.getLocalizedMessage());
                });
        addDisposable(disposable);
    }
}
